s<template>
  <base-breadcrumb>
    <template>
      <a-card class="table-page-search-wrapper">
        <titleName title="基本信息"></titleName>
        <!-- <a-button type="primary" @click="onSubmit">基本信息保存</a-button> -->
        <a-form-model ref="ruleForm" :model="form" :rules="rules" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }">
          <a-row :gutter="24">
            <a-col :md="16" :sm="16">
              <a-form-model-item label="所属单位" prop="project" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }">
                <org-tree-select v-model="form.projectId"
                                 disabled
                                 is-auto-select-first
                                  checkStrictly @select="selectOrg" @getProjectInfo="getOrganizePeopleList"></org-tree-select>
              </a-form-model-item>
            </a-col>
<!-- 
            <a-col :md="8" :sm="8">
              <a-form-model-item label="责任书类型" prop="responsibilityTypeId">
                <Selector v-model="form.responsibilityTypeId" selectType="20" urlType="commercial" :disabled="auditStatus === 'SUBMITTED'"></Selector>
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8">
              <a-form-model-item label="名称" prop="name">
                <BaseInput placeholder="请输入" v-model="form.name" :disabled="auditStatus === 'SUBMITTED'" />
              </a-form-model-item>
            </a-col> -->
            <a-col :md="8" :sm="8">
            <a-form-model-item label="签订完成日期" prop="signFinishDate">
              <a-date-picker v-model="form.signFinishDate"
                             @change="(date, dateString) => getTime(date, dateString, 'form', 'signFinishDate')" />
              <!-- <a-input  v-model="form.bidDate" :disabled="pageType == 'looks'" /> -->
            </a-form-model-item>
          </a-col>
            <a-col :md="8" :sm="8">
            <a-form-model-item label="填报人" prop="creatorName">
              <a-input  v-model="form.creatorName" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="填报时间：" prop="createTime">
<!--              <a-date-picker v-model="form.createTime"-->
<!--                             disabled @change="(date, dateString) => getTime(date, dateString, 'form', 'informantTime')" />-->
               <a-input  v-model="form.createTime" disabled />
            </a-form-model-item>
          </a-col>
          </a-row>
        </a-form-model>
      </a-card>
    </template>

    <a-modal title="岗位责任书" :visible="visible" :width="1010" @cancel="closeModal()" @ok="submitModal()">
      <a-form-model ref="ruleModalForm" :model="modalForm" :rules="modalRules" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }">
        <a-row :gutter="24">
          <!-- <a-col :md="12" :sm="12">
                        <a-form-model-item label="人员" prop="employeeId">
                            <SelectEmployees
                                placeholder="请选择"
                                v-model="modalForm.employeeId"
                                :form="form"
                                keyValue="deptName"
                            ></SelectEmployees>
                        </a-form-model-item>
                    </a-col> -->

          <a-col :md="12" :sm="12">
            <a-form-model-item label="人员" prop="employeeId">
              <a-select placeholder="请选择" v-model="modalForm.employeeId">
                <a-spin v-if="fetchingOrganizePeopleList" slot="notFoundContent" size="small" />
                <a-select-option v-for="i in organizePeopleList" :key="i.employeeId" :value="i.employeeId">{{ i.employeeName }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :md="12" :sm="12">
            <!--   @change="getEmployees" -->
            <a-form-model-item label="所属部门" prop="dept">
              <SelectDepartment placeholder="请选择" v-model="modalForm.dept" :form="form" :isClear="id == ''" :isObj="isObj" keyValue="project" labelInValue></SelectDepartment>
            </a-form-model-item>
          </a-col>
          <a-col :md="12" :sm="12">
            <a-form-model-item label="责任书名称" prop="responsibilityBook">
              <a-input  v-model="modalForm.responsibilityBook" />
            </a-form-model-item>
          </a-col>
          <a-col :md="12" :sm="12">
            <a-form-model-item label="签订日期" prop="signDate">
              <a-date-picker placeholder="请选择" v-model="modalForm.signDate" />
            </a-form-model-item>
          </a-col>
          <a-col :md="24" :sm="24">
            <a-form-model-item label="岗位责任书文件">
              <l-table v-if="visible" :delRequest="false" @fileArrysData="fileArrysData" :uploadArrys="modalForm.fileList" businessCode="BM16"></l-table>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>
    <!-- 附件 -->
    <a-card>
      <titleName title="岗位责任书清单"></titleName>
      <a-button class="mb20" type="primary" @click="handleAdd">添加行</a-button>
      <s-table ref="table" size="default" rowKey="key" :data="loadData" :alert="true" show-size-changer show-quick-jumper :showPagination="false" row-key="id" :columns="enclosure">
        <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
        <!-- 操作 -->
        <span slot="fileList" slot-scope="text, record">
          <template>
            <span v-for="(item, idx) in record.fileList" :key="idx">
              <a :href="'/api/ycloud-file-center/oper/download?access_token=' + token + '&fileId=' + item.fileId">{{ item.fileName }}{{ item.suffixName }}</a> </span
            >&nbsp;
          </template>
        </span>
        <span slot="action" slot-scope="text, record, index">
          <span>
            <a @click="addEdit(record, index)">编辑</a>
            <a-divider type="vertical" />
          </span>
          <a-popconfirm title="确定要删除?" @confirm="() => delItem(index)">
            <a>删除</a>
          </a-popconfirm>
          <!-- <a @click="delItem(index)">删除</a> -->
        </span>
      </s-table>
    </a-card>
    <!-- 弹框 -->
    <!-- <EditFrom :visible="visible" @cancel="handleCancel" :model="transmitList" @handleChange="handleOk"></EditFrom> -->
    <div class="tool-btns mb20 page-btn-right-top">
<!--      <a-button :loading="loading.DELETE" v-if="id != '' && form.auditStatus == 'DRAFT'" type="danger" @click="deleteDraft">删除草稿</a-button>-->
      <a-button :loading="loading.DRAFT" class="ml20" type="primary" @click="submitForm('DRAFT')">保存草稿</a-button>
      <a-button :loading="loading.SUBMITTED" class="ml20" type="primary" @click="submitForm('SUBMITTED')">提交</a-button>
      <a-button class="ml20" type="primary" @click="closeForm">关闭</a-button>
    </div>
  </base-breadcrumb>
</template>

<script>
import { detailed, rewrite, recordRow, eliminate, merchantFind } from '@/api/businessAffairs/postReporting'
import { getOrganizePeopleList } from '@/api/safetySupervision/emergencyDrill'
import SelectDepartment from '@/components/Select/SelectDepartment' // 部门
import { STable } from '@/components'
import Vue from 'vue'
const enclosure = [
  {
    title: '序号',
    width: '80px',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '姓名',
    dataIndex: 'employeeName'
  },
  {
    title: '所属部门',
    dataIndex: 'deptName',
    width: '105px',
  },
  {
    title: '责任书名称',
    dataIndex: 'responsibilityBook',
    width: '150px',
  },
  {
    title: '签订日期',
    dataIndex: 'signDate',
    width: '100px',
  },
  {
    title: '岗位责任书文件',
    width: '45%',
    dataIndex: 'fileList',
    scopedSlots: { customRender: 'fileList' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '20%',
    scopedSlots: { customRender: 'action' }
  }
]
import moment from 'moment'
export default {
  name: 'a' + Date.now(),
  components: {
    SelectDepartment,
    STable
  },
  mounted() {
    this.token = Vue.getAcloudProvider().getAccessToken()
    this.id = this.$route.query.id || ''
    if (this.$route.query.id) {
      detailed(this.$route.query.id).then((res) => {
        this.form = {
          ...res.data,
          project: { key: res.data.projectId, lable: res.data.projectName },
          dept: { key: res.data.deptNameId, lable: res.data.deptName }
        }
          this.form.creatorName = this.$userInfo().name
          this.form.createTime = moment().format("YYYY-MM-DD")
        this.modalForm.dept = {
          // key: res.data.deptNameId,
          // lable: res.data.deptName
        }
        this.$refs.table.refresh(true)
        this.getOrganizePeopleList()
      })
    }
    if (this.$route.query.type == 'view') {
      this.$route.meta.title = '岗位责任书查看'
    } else {
      this.$route.meta.title = this.id == '' ? '岗位责任书新增' : '岗位责任书编辑'
    }
  },
  handleOk(val) {
    console.log(val)
  },
  data() {
    this.enclosure = enclosure
    return {
      auditStatus: this.$route.query.auditStatus,
      id: '',
      modalForm: {
        fileList: [],
        dept: { key: '', lable: '' }
      },
      loading: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false
      },
      visible: false,
      form: {
        responsibilityTypeId: '',
        name: '',
        jobResponsibilityVOS: [],
        project: { key: '', lable: '' }
        // deptName: { key: '', lable: '' },
      },
      isObj: true,
      isEdit: false,
      rules: {
        signFinishDate: [{ required: true, message: '请选择签订完成日期', trigger: 'change' }],
        // branchComId: [{ required: true, message: '请选择分公司', trigger: 'change' }],
        // project: [{ required: true, message: '请选择项目', trigger: 'change' }],
        // // deptName: [{ required: true, message: '请选择部门', trigger: 'change' }],
        // responsibilityTypeId: [{ required: true, message: '请输入责任书类型', trigger: 'change' }],
        // name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      },
      modalRules: {
        signDate: [{ required: true, message: '请选择签订日期', trigger: 'change' }],
        employeeId: [{ required: true, message: '请选择人员', trigger: 'change' }],
        dept: [{ required: true, message: '请选择部门', trigger: 'change' }],
        responsibilityBook: [{ required: true, message: '请填写责任书名称'}],
        
      },
      employees: [],
      fetchingOrganizePeopleList: false,
      organizePeopleList: [],
      loadData: (parameter) => {
        // const requestParameters = Object.assign({}, parameter, this.queryParam)
        return new Promise((resolve, reject) => {
          resolve({
            data: this.form.jobResponsibilityVOS
          })
        })
      },
      validateState: false //是否可提交保存
    }
  },
  methods: {
    getTime(date, dateString, type, name) {
      this[type][name] = dateString
      console.log(this[type][name])
    },
    selectOrg(val) {
      if (val && val.length) {
        this.form.branchComId = val[val.length - 2].orgId
        this.form.project = { key: val[val.length - 1].projectId, lable: val[val.length - 1].projectName }
      }
      console.log('this.formthis.form',this.form)
    },
    //获取项目下的人员列表
    getOrganizePeopleList() {
      if (!this.form.project.key) return
      // if (!this.id) {
      //     this.$nextTick(() => {
      //         this.form.name = this.form.project.label
      //     })
      // }
      let params = {
        id: this.form.project.key
      }
      this.organizePeopleList = []
      this.fetchingOrganizePeopleList = true
      getOrganizePeopleList(params).then((res) => {
        this.fetchingOrganizePeopleList = false
        let obj = {}
        res.data = res.data.reduce((cur, next) => {
          obj[next.employeeId] ? '' : (obj[next.employeeId] = true && cur.push(next))
          return cur
        }, []) //设置cur默认类型为数组，并且初始值为空的数组
        this.organizePeopleList = res.data || []
      })
    },
    // changeDeptName() {
    //     if (!this.id) {
    //         this.$nextTick(() => {
    //             this.form.name = this.form.project.label + this.form.deptName.label + '岗位责任书'
    //         })
    //     }
    // },
    //根据部门获取部门下的人员列表
    getEmployees() {
      let data = {
        pageSize: 1,
        pageNumber: 100,
        orgId: this.modalForm.dept.key
      }
      getEmployees(data).then((res) => {
        if (res.status === 200) {
          this.employees = res.data.list
        } else {
          this.$message.error('err:', res.message)
        }
      })
    },
    delItem(idx) {
      this.form.jobResponsibilityVOS.splice(idx, 1)
      this.$refs.table.refresh(true)
    },
    fileArrysData(val) {
      this.modalForm.fileList = val
    },
    closeModal() {
      this.modalForm = { fileList: [] }
      this.visible = false
    },
    submitModal() {
      if (this.modalForm.fileList.length == 0) {
        this.$message.error('请上传岗位责任书')
        return
      }
      this.$refs.ruleModalForm.validate((valid) => {
        if (valid) {
          if (typeof this.modalForm.signDate != 'string') {
            this.modalForm.signDate = this.modalForm.signDate.format('YYYY-MM-DD')
          }
          //根据项目查询人员逻辑
          this.modalForm.employeeName = this.organizePeopleList.filter((item) => this.modalForm.employeeId == item.employeeId)[0].employeeName
          this.modalForm.deptName = this.modalForm.dept.label
          this.modalForm.deptNameId = this.modalForm.dept.key
          if (!this.isEdit) {
            this.form.jobResponsibilityVOS.push(this.modalForm)
          } else {
            this.form.jobResponsibilityVOS[this.modalForm.index] = this.modalForm
          }
          this.$refs.table.refresh(true)
          this.isEdit = true
          this.visible = false
          this.modalForm = { fileList: [] }
        }
      })
    },
    addEdit(data, index) {
      this.isEdit = true
      this.modalForm = this.$clone(data)
      this.modalForm.dept = {
        key: this.modalForm.deptNameId,
        lable: this.modalForm.deptName
      }
      this.modalForm.index = index
      this.visible = true
    },
    handleAdd() {
      this.isEdit = false
      this.visible = true
    },
    // 删除草稿
    deleteDraft(e) {
      let that = this
      that.$confirm({
        title: '温馨提示',
        content: '确定是否删除数据？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          return eliminate({ id: that.id })
            .then((res) => {
              that.$message.success('删除成功！')
              that.closeForm()
            })
            .catch((res) => {
              that.$message.warning('删除失败！')
            })
        }
      })
    },
    // deleteDraft() {
    //     this.loading.DELETE = true
    //     eliminate({ id: this.id }).then((res) => {
    //         this.loading.DELETE = false
    //         if (res.data.code === 200) {
    //             this.$message.success('删除成功')
    //             this.closeForm()
    //         } else {
    //             this.$message.error('删除失败')
    //         }
    //     })
    // },
    closeForm() {
      if (this.isAudit) {
        window.close()
      } else {
        this.$multiTab.close(this.$route.fullpath)
      }
    },
    //每个项目只能增加1条重要岗位类型的责任书、一条一般岗位的责任书
    handleValidate() {},
    // 提交按钮
    async submitForm(auditStatus) {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.loading[auditStatus] = true
          this.form.projectId = this.form.project.key
          this.form.auditStatus = auditStatus
          // delete this.form.project
          if (this.$route.query.id) {
            //每个项目，只能增加1条重要岗位类型的责任书、一条一般岗位的责任书判断
            rewrite(this.form).then((res) => {
              this.loading[auditStatus] = false
              this.$refs.ruleForm.resetFields()
              if (res.code === 200) {
                this.$message.success(auditStatus === 'SUBMITTED' ? '提交成功': '保存草稿成功')
                this.closeForm()
              } else {
                this.$message.warning('编辑失败')
              }
            })
          } else {
            //每个项目，只能增加1条重要岗位类型的责任书、一条一般岗位的责任书判断
            // let params = {
            //   projectId: this.form.project.key,
            //   responsibilityTypeId: this.form.responsibilityTypeId
            // }
            // merchantFind(params).then((res) => {
            //   if (res.data.message === 'true') {
                //可新增
                recordRow(this.form).then((res) => {
                  this.loading[auditStatus] = false
                  this.$refs.ruleForm.resetFields()
                  if (res.code === 200) {
                    this.$message.success('保存成功')
                    this.closeForm()
                  } else {
                    this.$message.warning('保存失败')
                  }

                })
              // } else {
              //   //已存在
              //   this.$info({
              //     title: '温馨提示',
              //     content: '每个项目只能增加1条重要岗位责任书、1条一般岗位的责任书',
              //     cancelText: '关闭'
              //   })
              //   this.loading[auditStatus] = false
              // }
            // })
          }
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
@deep: ~'>>>';
.tool-btns {
  display: flex;
  justify-content: flex-end;
  @{deep} .ant-btn + .ant-btn {
    margin-left: 12px;
  }
}
</style>
